const {blog_tag} = require("@/model");

class TagService {

  async getTagList({ pageSize = 10, pageIndex = 1 }) {
    if(pageSize < 1) { // 获取全部
      const res = await blog_tag.findAll();
      return {
        total: res.length,
        list: res,
      };
    }
    // 分页
    const offset = (pageIndex - 1) * pageSize;
    const { count, rows } = await blog_tag.findAndCountAll({
      offset,
      limit: pageSize,
      distinct: true, 
    });
    return {
      total: count,
      list: rows,
      pageIndex,
      totalPage: Math.ceil(count / pageSize),
    };
  }

  async addTag(name) { 
    const res = await blog_tag.create({ // 创建标签
      name,
    });
    return res.dataValues;
  }

  async deleteTag(id) { // 删除标签
    const res = await blog_tag.destroy({
      where: {
        id,
      },
    });
    return res;
  }

  async updateTag({id, name}) { // 更新标签
    const res = await blog_tag.update(
      { name },
      {
        where: {
          id,
        },
      }
    );
    return res;
  }
}

module.exports = new TagService();